package com.example.analyzevisio.controller;


import com.example.analyzevisio.utis.Json;
import com.example.analyzevisio.utis.VSDXParser;
import com.example.analyzevisio.utis.anaiyvisio;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipInputStream;

import static com.example.analyzevisio.utis.HttpRestTemplate.post;
import static com.example.analyzevisio.utis.Obtain.deleteDirectoryContents;


@RestController
@CrossOrigin
public class VSDXController {

    //临时文件保存地址
    @Value("${file.outputFolder}")
    private String outputFolder;
//       String outputFolder = "C:\\Users\\ms206\\Desktop\\visio图\\代码解压\\";

    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        String folder = "C:\\Users\\ms206\\Desktop\\visio图\\错误节点.vsdx";
        map.put("fileName",folder);
        VSDXController vsdxController = new VSDXController();
        vsdxController.uploadFile(map);
    }
    @PostMapping("/upload")
    public void uploadFile(@RequestBody Map<String, String> data) {
        String str = null;

        // 定义目录路径
        Path dir = Paths.get(outputFolder);
        try {
            // 判断目录是否存在，如果不存在则创建
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
            } else {
                // 删除目录下的所有文件和子目录
                deleteDirectoryContents(dir);
            }

            //解压visio
            anaiyvisio.unzip(data.get("fileName"),outputFolder);


            // 解析并转换为JSON
            String json = VSDXParser.parsePageXml(outputFolder + "visio\\Pages\\Page1.xml",outputFolder + "visio\\masters\\masters.xml");
            String escapedJson = json.replace("\"", "\\\"");
             str = "{\n" +
                    "  \\\"cells\\\": "+escapedJson+"  \n" +
                    "}";


            Json json1 = new Json();
            System.out.println(str);
            post(json1.addJson(str));

        } catch (Exception e) {
//            logger.error("An error occurred during processing: " + e.getMessage());
            throw new RuntimeException("报错出口"+ e);
//            return "暂不支持水平泳道";
        }
    }
}
